package com.prs.crm.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.context.Constrains;
import com.prs.crm.log.ILogger;
import com.prs.crm.service.sys.impl.LogServiceImpl;

public class LogInterceptor implements MethodInterceptor{
	
	private static final Logger log = Logger.getLogger(LogInterceptor.class);
	
	@Autowired
	private ILogger logger;
	
	public void setLogger(ILogger logger) {
		this.logger = logger;
	}

	public ILogger getLogger() {
		return logger;
	}

	public Object invoke(final MethodInvocation invocation) throws Throwable {
		Object result =  invocation.proceed();
		try
		{
			String methodName = invocation.getMethod().getName();
			if (methodName.equals("save") || methodName.equals("remove"))
			{
				if (processValide(invocation.getThis().getClass()))
				{
					int type = getOperType(invocation.getArguments(),methodName);
					if (type>0)
					{
						logger.logOper(invocation.getArguments()[0].getClass(),
								PropertyUtils.getProperty(invocation.getArguments()[0], "id"), type);
					}
				}
			}
		}
		catch (Exception e)
		{
			log.error(e);
		}
		return result;
	}
	
	private boolean processValide(Class<?> cls)
	{
		if (!cls.equals(LogServiceImpl.class)
				&& cls.getName().indexOf("com.prs.crm.service.sys")==0)
		{
			return true;
		}
		return false;
	}
	
	private int getOperType(Object[] arguments,String methodName)
	{
		try
		{
			if (arguments.length==1)
			{
				Object entity = arguments[0];
				if (methodName.equals("save"))
				{
					if (PropertyUtils.getProperty(entity, "id")!=null)
					{
						return Constrains.LOGTYPE_UPDATE;
					}
					else
					{
						return Constrains.LOGTYPE_ADD;
					}
				}
				else if (methodName.equals("remove"))
				{
					return Constrains.LOGTYPE_REMOVE;
				}
			}
			return 0;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return 0;
		}
	}
}
